//
//  TTLoginViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/15.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTLoginViewController.h"
#import "TTPwdLoginView.h"
#import "TTVerifyLoginView.h"
#import "TTRegisterViewController.h"
#import "TTLoginModel.h"

@interface TTLoginViewController ()

@property (nonatomic, strong) TTPwdLoginView *pwdLoginView;
@property (nonatomic, strong) TTVerifyLoginView *verifyLoginView;
@property (nonatomic, strong) UIButton *changeBtn;  // 密码验证码切换按钮
@property (nonatomic, strong) UIButton *registerBtn;  // 注册
@property (nonatomic, strong) UIButton *loginBtn;   // 登录

@property (nonatomic, copy) dispatch_block_t closeBlock;

@end

@implementation TTLoginViewController

- (instancetype)initWithCloseBlock:(dispatch_block_t)closeBlock
{
    self = [super init];
    if (self) {
        self.closeBlock = closeBlock;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = [UIColor whiteColor];
    
    if (![TTLoginSingle sharedSingle].mineDianpuShow) {
        UIImage *rightImage = [[UIImage imageNamed:@"login_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightImage style:UIBarButtonItemStyleDone target:self action:@selector(dismissAction)];
    }
    
    
    if (!self.fromRegister) {
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    [self setupSubviews];
    
    [self checkStatusChange];
    
    
    
}

- (void)dismissAction
{
    if (self.closeBlock) {
        self.closeBlock();
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 发送验证码
- (void)sendVerifyCode
{
    NSString *phoneNum = [self.verifyLoginView.phoneTF.text removeBlank];
    NSDictionary *dic = @{
                          @"param.mobile" : phoneNum
                          };
    [[LLNetworkManagerTool sharedManager] postUrlString:sendVerifyCode_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self.view makeToast:@"验证码发送成功" duration:1.0 position:CSToastPositionCenter];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    } showLoadingInView:self.view];
    
}

// 登录
- (void)loginBtnClick
{
    // 密码登录
    NSString *phoneNum = [self.pwdLoginView.phoneTF.text removeBlank];
    NSString *pwdString = self.pwdLoginView.pwdTF.text;
    NSString *loginField = @"param.password";
    if (!self.changeBtn.selected) {
        // 验证码登录
        phoneNum = [self.verifyLoginView.phoneTF.text removeBlank];
        pwdString = self.verifyLoginView.verifyTF.text;
        loginField = @"param.mobileVerifyCode";
    }
    NSDictionary *dic = @{
        @"param.mobile" : phoneNum,
        loginField : pwdString
    };
    [MBProgressHUD showLoadingAnimationOnView:self.view];
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:login_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self)
        
        TTLoginModel *model = [TTLoginModel modelWithJSON:responseObject];
        
        [MBProgressHUD dismissAnimationOnView:self.view];
        
        if (model.State.intValue == 0) {
            LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"登录异常" message:@"您的账号已经锁定，无法正常使用。" confirmTitle:@"确认" confirmBlock:^BOOL{
                return YES;
            }];
            [TYShowAlertView showAlertViewWithView:alertView backgoundTapDismissEnable:YES];
        } else {
            // 保存
            [TTLoginSingle setupUserDataWithModel:model];
            // 获取批发商身份信息
            [TTCommonNetData getVipLevelSuccess:^(TTUserModel * _Nonnull userModel) {
                [[TTLoginSingle sharedSingle].loginSubject sendNext:@(1)];
                [self dismissViewControllerAnimated:YES completion:nil];
            } failure:^{}];
            
            // 请求购物车数据
            [TTCommonNetData getShopCartCodeInfoSuccess:^(NSArray * _Nonnull cartCodeArray, int shopCount) {} failure:^{
                [MBProgressHUD dismissAnimationOnView:self.view];
            }];
            
        }
        
        
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        [MBProgressHUD dismissAnimationOnView:self.view];
    } showLoadingInView:nil];

}

// 注册
- (void)registerBtnClick
{
    BOOL noRegisertVC = YES;
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[TTRegisterViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            noRegisertVC = NO;
            break;
        }
    }
    
    if (noRegisertVC) {
        TTRegisterViewController *registerVC = [[TTRegisterViewController alloc] init];
        [self.navigationController pushViewController:registerVC animated:YES];
    }
}

// 切换登录方式
- (void)changeBtnClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.pwdLoginView.hidden = !sender.selected;
    self.verifyLoginView.hidden = !self.pwdLoginView.hidden;
    
    if (!sender.selected) {
        self.verifyLoginView.phoneTF.text = self.pwdLoginView.phoneTF.text;
        self.loginBtn.enabled = self.verifyLoginView.phoneTF.text.length >= 13 && self.verifyLoginView.verifyTF.text.length == 4;
        self.verifyLoginView.verifyBtn.enabled = self.verifyLoginView.phoneTF.text.length >= 13;
        [self.verifyLoginView.phoneTF becomeFirstResponder];
    } else {
        self.pwdLoginView.phoneTF.text = self.verifyLoginView.phoneTF.text;
        self.loginBtn.enabled = self.pwdLoginView.phoneTF.text.length >= 13 && self.pwdLoginView.pwdTF.text.length == 6;
        [self.pwdLoginView.phoneTF becomeFirstResponder];
    }
    
    UIColor *color = self.loginBtn.enabled ? kMainColor : COLOR(200, 200, 200, 1);
    self.loginBtn.backgroundColor = color;
    
}


- (void)checkStatusChange
{
    // 发送验证码按钮
    @weakify(self)
    [[RACSignal combineLatest:@[self.verifyLoginView.phoneTF.rac_textSignal] reduce:^id _Nonnull(NSString *text){
        return text;
    }] subscribeNext:^(NSString *  _Nullable x) {
        @strongify(self)
        self.verifyLoginView.verifyBtn.enabled = x.length >= 13;
    }];
    
    // 登录按钮
    [[RACSignal combineLatest:@[self.pwdLoginView.phoneTF.rac_textSignal, self.pwdLoginView.pwdTF.rac_textSignal] reduce:^id _Nonnull(NSString *phone, NSString *pwd){
        return @(phone.length >= 13 && pwd.length >= 4);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.loginBtn.enabled = [x boolValue];
        UIColor *color = [x boolValue] ? kMainColor : COLOR(200, 200, 200, 1);
        self.loginBtn.backgroundColor = color;
    }];
    
    [[RACSignal combineLatest:@[self.verifyLoginView.phoneTF.rac_textSignal, self.verifyLoginView.verifyTF.rac_textSignal] reduce:^id _Nonnull(NSString *phone, NSString *verifyCode){
        return @(phone.length >= 13 && verifyCode.length == 4);
    }] subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        self.loginBtn.enabled = [x boolValue];
        UIColor *color = [x boolValue] ? kMainColor : COLOR(200, 200, 200, 1);
        self.loginBtn.backgroundColor = color;
    }];
}

- (void)setupSubviews
{
    UILabel *topLabel = [UILabel labelWithTitle:@"登录淘托" color:UIColorHex(333333) fontSize:28];
    topLabel.frame = CGRectMake(35 * kScale, 50 * kScale, 150 * kScale, 30 * kScale);
    [self.view addSubview:topLabel];
    
    _pwdLoginView = [[TTPwdLoginView alloc] initWithFrame:CGRectMake(35 * kScale, topLabel.bottom + 75 * kScale, self.view.width - 70 * kScale, 110)];
    _pwdLoginView.hidden = YES;
    [self.view addSubview:_pwdLoginView];
    
    _verifyLoginView = [[TTVerifyLoginView alloc] initWithFrame:self.pwdLoginView.frame];
    [self.view addSubview:_verifyLoginView];
    @weakify(self)
    _verifyLoginView.verifyBtn.sendVerifyCode = ^(UIButton * _Nonnull btn) {
        @strongify(self)
        [self sendVerifyCode];
    };
    
    _changeBtn = [UIButton createButtonWithNormalTitle:@"密码登录" selectedTitle:@"验证码登录" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:15] target:self action:@selector(changeBtnClick:)];
    [self.view addSubview:_changeBtn];
    [_changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pwdLoginView.mas_bottom).mas_offset(10);
        make.left.equalTo(self.pwdLoginView);
    }];
    
    _registerBtn = [UIButton createButtonWithTitle:@"新用户注册" titleColor:kMainColor titleFont:[UIFont systemFontOfSize:15] backgroundColor:[UIColor whiteColor] target:self action:@selector(registerBtnClick)];
    [self.view addSubview:_registerBtn];
    [_registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.changeBtn);
        make.right.equalTo(self.pwdLoginView);
    }];
    
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_loginBtn setBackgroundColor:COLOR(200, 200, 200, 1)];
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    _loginBtn.layer.cornerRadius = 45 * kScale * 0.5;
    [_loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_loginBtn];
    [_loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.changeBtn.mas_bottom).mas_offset(30);
        make.left.right.equalTo(self.pwdLoginView);
        make.height.mas_equalTo(45 * kScale);
    }];
    
}

- (void)dealloc
{
    NSLog(@"登录页面释放了");
}


@end
